/*
 * @Author: wwssaabb
 * @Date: 2021-12-11 15:06:05
 * @LastEditTime: 2021-12-11 15:34:29
 * @FilePath: \handwritten-code\main\JSONP.js
 */

//JSONP ,处理跨域的方式之一，优点：兼容性好，缺点：只支持GET请求
//原理是通过script标签不受同源策略的限制=>需要创建script标签

const jsonp = ({
  url,
  params,
  callbackName
}) => {
  const path = Object.keys(params).reduce((pre, cur, index) => pre += (index === 0 ? '?' : '&') + `${cur}=${params[cur]}`, url)
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = path
    script.type = 'text/javascript'
    document.body.appendChild(script)
    window[callbackName] = data => {
      resolve(data)
      document.removeChild(script)
    }
  })
}

jsonp({
  url: 'http://www.baidu.com',
  params: {
    name: 'aaa',
    age: 16
  },
  callbackName: 'cb'
})